/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

/**
 * 微快递寄件黑名单
 *  */
import React, { useEffect, useRef, useState } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import { ProFormText, ModalForm, ProFormTextArea } from '@ant-design/pro-form';
import ProTable from '@ant-design/pro-table';
import {
  wkdInnList,
  wkdPullBlack,
  getBrandList,
  wkdBlackListDel,
} from '@/services/mini/wdkPullBlack';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import { Button, message, Tree } from 'antd';
import { TableItem } from './index.d';
import styles from './index.less';

const NoticeVerify: React.FC = () => {
  const actionRef = useRef<ActionType>();
  const [modalVisit, setModalVisit] = useState<boolean>(false);
  const [limitList, setLimitList] = useState<any>([]);
  const [limitData, setLimitData] = useState<string[]>([]);
  const [recoed, setRecoed] = useState<any>({});
  const [remark, setRemark] = useState<string>('');

  const handleOption = (data: TableItem) => {
    setLimitData(data.intercept_brand);
    setRemark(data.remark);
    setRecoed(data);
    setModalVisit(true);
  };

  const columns: ProColumns<TableItem>[] = [
    {
      title: '',
      hideInTable: true,
      renderFormItem: () => {
        return (
          <ProFormText
            rules={[{ pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: '请输入正确手机号' }]}
            label='手机号'
            name='mobile'
            placeholder='请输入正确手机号'
          />
        );
      },
    },
    {
      title: '',
      hideInTable: true,
      renderFormItem: () => {
        return <ProFormText label='用户ID' name='user_id' placeholder='请输入正确用户ID' />;
      },
    },
    {
      title: '用户ID',
      dataIndex: 'id',
      align: 'center',
      width: 80,
      search: false,
      ellipsis: true,
    },
    {
      title: '用户手机号',
      dataIndex: 'username',
      align: 'center',
      width: 120,
      search: false,
      ellipsis: true,
    },
    {
      title: '用户状态',
      dataIndex: 'intercept_brand',
      align: 'center',
      search: false,
      ellipsis: true,
      width: 100,
      render: (_, data) => {
        return <>{data.intercept_brand.length > 0 ? '限制' : '正常'}</>;
      },
    },
    {
      title: '渠道',
      dataIndex: 'channel',
      align: 'center',
      search: false,
      ellipsis: true,
      width: 80,
      render: (_, data: any) => {
        const platform = {
          mina: '微信',
          aliapp: '支付宝',
          huawei_quickapp: '华为',
          baiduapp: '百度',
        };
        return platform[data.channel];
      },
    },
    {
      title: '品牌限制',
      dataIndex: 'intercept_brand',
      align: 'center',
      search: false,
      ellipsis: true,
      width: 300,
      render: (_, data) =>
        data.intercept_brand.length > 0
          ? limitList[0].children
              .filter((item: any) => data.intercept_brand.includes(item.key))
              .map((item1: any) => item1.title)
              .join(',')
          : '-',
    },
    {
      title: '操作时间',
      dataIndex: 'operate_at',
      align: 'center',
      search: false,
      ellipsis: true,
      width: 200,
    },
    {
      title: '备注',
      dataIndex: 'remark',
      align: 'center',
      search: false,
      ellipsis: true,
      width: 200,
    },
    {
      title: '操作',
      dataIndex: 'option',
      align: 'center',
      search: false,
      ellipsis: true,
      fixed: 'right',
      width: 120,
      render: (_, data) => {
        return (
          <Button type='primary' size='small' onClick={handleOption.bind(null, data)}>
            品牌限制
          </Button>
        );
      },
    },
  ];

  const handleTreeCheck = (data: any) => {
    setLimitData(data.filter((item: any) => !!item));
  };

  const onSubmit = (data: any) => {
    let code: number = 0;
    if (limitData.length) {
      wkdPullBlack({
        intercept_brand: limitData.join(','),
        ...data,
        user_id: recoed.id,
        channel: recoed.channel,
      }).then((res) => {
        code = res.code;
        message.info(res.msg);
      });
    } else {
      wkdBlackListDel({ user_id: recoed.id, channel: recoed.channel }).then((res) => {
        code = res.code;
        message.info(res.msg);
      });
    }
    if (code == 0) {
      setModalVisit(false);
      actionRef.current?.reload();
    }
  };

  const getList = (data: any) => {
    const { mobile, user_id } = data;
    if (mobile || user_id) {
      return wkdInnList(data);
    } else {
      message.error('请输入手机号或用户ID');
      return {};
    }
  };

  useEffect(() => {
    getBrandList().then(({ data }: any) => {
      const limits = [
        {
          title: '全部',
          key: '',
          children: data.map((item: any) => ({ title: item.nickname, key: item.brand })),
        },
      ];
      setLimitList(limits);
    });
  }, []);

  return (
    <PageContainer className={styles.main} title='微快递寄件黑名单'>
      <ProTable<TableItem>
        actionRef={actionRef}
        manualRequest
        pagination={false}
        rowKey='index'
        request={getList}
        columns={columns}
        options={false}
        expandable={{
          rowExpandable: () => false,
        }}
        search={{
          optionRender: (_, { form }) => [
            <Button
              key='phone'
              type='primary'
              onClick={() => {
                form?.submit();
              }}
            >
              搜索
            </Button>,
          ],
        }}
        scroll={{ x: 1100 }}
      />
      <ModalForm
        title='品牌限制'
        visible={modalVisit}
        onVisibleChange={setModalVisit}
        onFinish={onSubmit}
        initialValues={{
          remark: remark,
        }}
        modalProps={{
          destroyOnClose: true,
          width: 700,
        }}
      >
        <Tree
          className={styles.main__tree}
          checkable
          treeData={limitList}
          defaultExpandAll
          defaultCheckedKeys={limitData}
          onCheck={handleTreeCheck}
        />
        <ProFormTextArea name='remark' label='备注' placeholder='请输入备注' />
      </ModalForm>
    </PageContainer>
  );
};

export default NoticeVerify;
